#-*-  coding:utf-8 -*-

# https://max.book118.com/html/2017/0326/97200801.shtm
import base64
import io
import time

from pptx import Presentation
from PIL import Image
from pptx.util import Inches

from selenium import webdriver

options = webdriver.FirefoxOptions()
options.set_headless()
options.add_argument('--disable-gpu')
driver=webdriver.Firefox(firefox_options=options, executable_path=r'D:\geckodriver-v0.20.0-win64\geckodriver.exe')

driver.set_window_size(1366, 768)
driver.get("https://max.book118.com/html/2016/0918/54908764.shtm")

driver.find_element_by_xpath("/html/body/div[5]/div[2]/div[1]/div[4]/div/div[3]/div/div/div/a").click()
time.sleep(3)

driver.switch_to.frame("layer_view_iframe")
time.sleep(3)

# 创建ppt
prs = Presentation()

# 创建ppt首页
slide = prs.slides.add_slide(prs.slide_layouts[0])
title = slide.shapes.title
title.text = "数理方法参考导论"
subtitle = slide.placeholders[1]
subtitle.text = "——Arnold"

n = 0
while n < 55:
  driver.find_element_by_xpath('//*[@id="slide{}"]'.format(n))

  # 获取图像并裁切
  image = io.BytesIO(base64.b64decode(driver.get_screenshot_as_base64()))
  img = Image.open(image)
  region = img.crop((215, 0, 931, 537))
  region.save("./tmp.png")

  # 图片写入ppt文件
  slide = prs.slides.add_slide(prs.slide_layouts[1])
  slide.shapes.add_picture("./tmp.png", Inches(0), Inches(0))
  prs.save("数理方法参考导论.pptx")

  print("生成第%s页" % (n+1))

  # 模拟点击加载下一页
  driver.find_element_by_xpath('/html/body/div[3]/div[3]/div[1]/div[4]').click()
  time.sleep(5)

  n = n + 1

# 保存ppt
prs.save("数理方法参考导论.pptx")

print("completed!!!")
driver.quit()
